<script setup lang="ts">
import DefaultAvatar from '@/area/common/components/DefaultAvatar.vue';
import { Tickets, Remove, Plus } from '@element-plus/icons-vue'
import { inject, ref } from 'vue';
import { FindMemberOfRoleQueryRequest, PageInfo, type IdentityHttpService, type UserAccountDto, ResponseStatus } from '../service/identity-http.service';
import { ElMessage, ElMessageBox } from 'element-plus';

var httpService = inject<IdentityHttpService>('IdentityHttpService');

const props = defineProps({
	roleId: Number,
  queryString: String
});

defineExpose({ 
  showAddMemberDialog,
  loadMemberList
});

const memberList = ref<UserAccountDto[]>([]);
const pageInfo = ref({ index: 1, size: 10, total: 0 })
const memberListLoading = ref(false);
function loadMemberList() {
  let request = new FindMemberOfRoleQueryRequest();
  request.roleId = props.roleId;
  request.keyWords = props.queryString;
  request.pageInfo = new PageInfo();
  request.pageInfo.index = pageInfo.value.index;
  request.pageInfo.size = pageInfo.value.size;

  memberListLoading.value = true;
  httpService?.apiRoleFindMemberOfRole(request).then(result => {
    removeMemberLoading.value = new Map<number, boolean>();
    memberListLoading.value = false;
    memberList.value = result.data??[];
    pageInfo.value.total = result.totalCount??0;
    
    //创建控制移除成员时按钮longing显隐的map
    if(result && result.data && result?.data?.length > 0) {
      result.data.forEach(it => {
        removeMemberLoading.value.set(it.id!, false);
      });
    }
  });
}

//#region ----Add member start----
//Dialog part
const addMemberDialogVisable = ref(false);
function showAddMemberDialog() {
  addMemberDialogVisable.value = true;
}

//Auto complete part
const searchUsername = ref('');
const querySearch = (queryString: string, callback: (arg: any) => void) => {
  httpService?.apiUserAccountFindByKeyword(queryString).then(result => {
    callback(result);
  });
}

function onAutoCompleteCardSelect(item: any) {
  tagDatas.value.push(item);
}

//Tag and submit part
const tagDatas = ref<UserAccountDto[]>([]);

function onTagClose(index: number) {
  tagDatas.value.splice(index, 1);
}

const addMemberLoading = ref(false);
function addMemberSubmit() {
  let userIds = tagDatas.value.map(it => it.id!);
  addMemberLoading.value = true;
  httpService?.apiRoleAddMemberBluk(props.roleId, userIds).then(result => {
    addMemberLoading.value = false;
    if (result.status == ResponseStatus.Success) {
      addMemberDialogVisable.value = false;
      tagDatas.value = [];
      ElMessage({ type: 'success', message: result.message });
      loadMemberList();
    } else {
      ElMessage({ type: 'warning', message: result.message });
    }
  });
}
//#endregion ----Add member end----

const removeMemberLoading = ref(new Map<number, boolean>());
function removeMember(id: number) {
  ElMessageBox.confirm(
    '确认要将该用户移除吗？',
    '移除用户',
    { confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning' }
  ).then(() => {
    removeMemberLoading.value.set(id, true);
    httpService?.apiRoleRemoveMemberBluk(props.roleId, [id]).then(result => {
      removeMemberLoading.value.set(id, false);
      loadMemberList();
    });
  });
}
</script>

<template>
<el-table class="common-table" :data="memberList" v-loading="memberListLoading" style="width: 100%">
  <el-table-column label="" width="60">
    <template #default="scope">
      <DefaultAvatar :name="scope.row.userName"/>
    </template>
  </el-table-column>
  <el-table-column prop="userName" label="用户名"></el-table-column>
  <el-table-column prop="email" label="邮箱" />
  <el-table-column prop="phoneNumber" label="手机" />
  <el-table-column label="" width="200">
    <template #default="scope">
      <el-button :icon="Tickets" type="primary" text @click="$emit('detailClick', scope.row.id)">详情</el-button>
      <el-button :icon="Remove" type="primary" text :loading="removeMemberLoading.get(scope.row.id)" @click="removeMember(scope.row.id)">移除</el-button>
    </template>
  </el-table-column>
</el-table>

<div style="margin-top: 12px;display: flex;flex-direction: row-reverse;">
<el-pagination 
  v-model:current-page="pageInfo.index" v-model:page-size="pageInfo.size" :total="pageInfo.total"
  :page-sizes="[10, 20, 50, 100]" layout="sizes, prev, pager, next" 
  @size-change="loadMemberList()" @current-change="loadMemberList()"/>
</div>

<!-- Add Member Dialog -->
<el-dialog title="添加成员" v-model="addMemberDialogVisable" width="460px">
  <el-autocomplete style="width: 100%;" :trigger-on-focus="false" :debounce="500" 
    v-model="searchUsername" :fetch-suggestions="querySearch" clearable
    @select="onAutoCompleteCardSelect($event)">
    <template #default="{ item }">
      <div class="autocomplete-card">
        <div style="padding: 4px;margin: 0px 4px 0px -4px;">
          <DefaultAvatar :name="item?.userName" size="48px" font-size="22px"/>
        </div>
        <div>
          <div style="max-height: 24px;">
            <span class="card-name" style="font-size: 14px;">{{ item?.userName }}</span>
            <span class="card-other"><el-icon><Message /></el-icon>727164019@qq.com</span>
          </div>
          <div style="max-height: 24px;">
            <span class="card-other"><el-icon><Iphone /></el-icon>18698699075</span>
          </div>
        </div>
      </div>
    </template>
  </el-autocomplete>
  <div style="margin: 8px 0px;">
    <el-tag v-for="(tag, index) in tagDatas" style="margin-right: 4px;font-size: 16px;"
      size="large" :key="tag.id" closable type="primary" @close="onTagClose(index)">
      {{ tag.userName }}
    </el-tag>
  </div>
  <div style="text-align: right;">
    <el-button type="primary" :icon="Plus" :disabled="tagDatas.length == 0" :loading="addMemberLoading" @click="addMemberSubmit()">添加</el-button>
  </div>
</el-dialog>
</template>

<style lang="scss">

</style>